package com.wenjiang.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.wenjiang.common.annotation.RequireToken;
import com.wenjiang.common.constat.RedisKey;
import com.wenjiang.common.dto.AliPayParam;
import com.wenjiang.common.lang.Result;
import com.wenjiang.config.AliPayConfig;
import com.wenjiang.entity.AliPayBean;
import com.wenjiang.service.MallOrderService;
import com.wenjiang.service.impl.AliPayServiceImpl;
import com.wenjiang.common.util.JWTUtil;
import com.wenjiang.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/mallpay")
@Slf4j
public class MallPayController {

    @Autowired
    MallOrderService mallOrderService;

    @Autowired
    AliPayServiceImpl aliPayService;

    @Autowired
    AliPayConfig aliPayConfig;

    @Autowired
    RedisUtils redisUtils;




    /**
     * 普通支付接口
     */
    @RequestMapping("/pay")
    @RequireToken
    public Result payOrder(HttpServletRequest request, @RequestParam("goodId") String[]goodId,
                           @RequestParam("orderId")String orderId) throws IOException, EncodeException {

        String token = request.getHeader("token");

        Long userId = JWTUtil.getUserId(token);


        //判断订单是否过期 从redis取
        StringBuffer stringBuffer= new StringBuffer();
        stringBuffer.append(userId);



        for(String item:goodId){
            stringBuffer.append(item);
        }
        //不存在 key 即为订单过期
        if(!redisUtils.hasKey(RedisKey.redisOrderKey+stringBuffer.toString())){

            return  Result.fail(200,"订单已过期");
        }



        //可投递到消息队列
        Result result = mallOrderService.payOrder(Long.valueOf(orderId),userId,goodId);

        return result;

    }


    /**
     * 支付宝支付接口
     */

    @RequestMapping("/alipay")
    @RequireToken
    public  Object aliPay(HttpServletRequest request,@RequestBody AliPayParam aliPayParam) throws AlipayApiException, JsonProcessingException {

        //取参数 从redis 判断是否过期

        String token = request.getHeader("token");

        Long userId = JWTUtil.getUserId(token);


        //判断订单是否过期 从redis取
        StringBuffer stringBuffer= new StringBuffer();
        stringBuffer.append(userId);

        String[] goodId = aliPayParam.getGoodId();

        for(String item:goodId){
            stringBuffer.append(item);
        }
        //不存在 key 即为订单过期
        if(!redisUtils.hasKey(RedisKey.redisOrderKey+stringBuffer.toString())){

            return  Result.fail(200,"订单已过期");
        }


        AliPayBean aliPayBean= new AliPayBean();
        //赋值
        BeanUtil.copyProperties(aliPayParam,aliPayBean);
        aliPayBean.setSubject("支付宝订单");
        aliPayBean.setTotal_amount(aliPayParam.getTotal_amount());
        //根据rediskey的剩余时间 设置支付宝订单时间
        long expire = redisUtils.getExpire(RedisKey.redisOrderKey + stringBuffer.toString());
//        aliPayBean.setTimeout_express("1800");
        //这个生成支付的网页代码
        String alipay = aliPayService.alipay(aliPayBean);
        return alipay;
    }


    /**
     * 支付宝支付成功后回调接口（进行数据库操作）
     */
    @RequestMapping("/alipaysuccess")
    public String  aliPaySuccess(HttpServletRequest request) throws AlipayApiException {

        // 获取支付宝的请求信息
        Map<String, String> map = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        if(requestParams.isEmpty()) {
            return "failure";
        }
        // 将 Map<String,String[]> 转为 Map<String,String>
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }
        // 验签
        boolean signVerified = AlipaySignature.rsaCheckV1(map, aliPayConfig.getPublicKey(), aliPayConfig.getCharset(),aliPayConfig.getSignType());
        // 验签通过
        if (signVerified) {
            //支付成功后进行操作
            System.out.println("参数"+map);
            //修改订单状态
            String orderId = map.get("out_trade_no");
            //扣除商品数量
            mallOrderService.ailiPayOrder(Long.valueOf(orderId));

            //添加商品评论
        }
        return "success";

    }
}
